package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"home-hub/models"
)

type Home struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msd  string      `json:"msd"`
	Data interface{} `json:"data"`
}

func (h *Home) Add() {

	price, _ := h.GetFloat("price")
	num := h.GetString("num")
	name := h.GetString("name")
	tel := h.GetString("tel")
	names := h.GetString("names")
	mold := h.GetString("mold")
	home := models.Home{
		Price: price,
		Num:   num,
		Name:  name,
		Tel:   tel,
		Names: names,
		Mold:  mold,
	}
	err := models.DB.Create(&home).Error
	if err != nil {
		h.Data["json"] = Res{
			Code: 0,
			Msd:  "添加失败",
		}
		h.ServeJSON()
		return
	} else {
		h.Data["json"] = Res{
			Code: 200,
			Msd:  "添加成功",
		}
		h.ServeJSON()
	}
}
func (h *Home) List() {

	page, _ := h.GetInt("page", 1)
	size, _ := h.GetInt("size", 5)
	offset := (page - 1) * size
	query := models.DB.Model(&models.Home{})
	var count int64
	query.Count(&count)
	var home []models.Home
	err := query.Offset(offset).Limit(size).Find(&home).Error
	if err != nil {
		h.Data["json"] = Res{
			Code: 0,
			Msd:  "查询失败",
		}
		h.ServeJSON()
		return
	} else {
		Pagadata := make(map[string]interface{})
		Pagadata["count"] = count
		Pagadata["home"] = home
		h.Data["json"] = Res{
			Code: 200,
			Msd:  "查询成功",
			Data: home,
		}
		h.ServeJSON()
	}
}
